package com.cx.interceptor;

import java.io.PrintWriter;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cx.service.RedisService;

public class H5Interceptor implements HandlerInterceptor {
	
	@Resource
	private RedisService redisService;
	
    //在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
    	if ("OPTIONS".equals(request.getMethod())) {
    		return true; 
		}
    	
    	//获取请求路径
    	String path = request.getServletPath();
    	if( path.indexOf("/h5/index/") > -1 ||   //活动入口
    		path.indexOf("h5/activity/selectOngoingActPage") > -1  //获取进行中活动
    	  ){    
    		return true; 
    	}
    	//获取token
    	String token = request.getHeader("token");
    	if(!redisService.exists(token)){
    		response.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter printWriter = response.getWriter();    
            printWriter.write("{\"status\":\"-99\",\"errorMsg\":\"无效请求\",\"body\":\"\"}");    
            return false; 
    	}
        
    	return true; 
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //System.out.println("postHandle被调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //System.out.println("afterCompletion被调用");
    }
}
